import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  Animated,
  TextInput,
  Dimensions,
  TouchableOpacity
} from 'react-native';
import dismissKeyboard from 'dismissKeyboard';
import styles from './indexStyle';
import api from '../../services/api';
import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';

import EasemobChat from '../global/EasemobChat';

let winH = Dimensions.get('window').height;
let windowHeight = 175;

import JPushModule from 'jpush-react-native';

class LoginIndex extends Component {
    constructor(props) {
		super(props);

		this.state = {
            isShowPass: false,
            loadingShow: false,
            phone:"",
            passwd:"",
            scrollY: new Animated.Value(0),
		};
        this.reg_id = "";

		// this._getTabHeight = this._getTabHeight.bind(this);
		// this._onChangeTab = this._onChangeTab.bind(this);

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentWillMount() {
		// this._retrieveDetails();
        JPushModule.getRegistrationID((reg_id)=>{
            this.reg_id = reg_id;
        });
	}

    async _submitAction(){
        let {phone, passwd} = this.state;
        let {actions, dispatch} = this.props;

        if(!phone){
             this.refs.toast.show('请输入手机号');
             return;
        }

        if(!/^1[0-9]{10}$/.test(phone)){
            this.refs.toast.show('请输入正确的手机号');
            return;
        }

        if(!passwd){
             this.refs.toast.show('请输入密码');
             return;
        }

        this.setState({loadingShow: true});
        let res = await api.post("/housekeeper/login",{phone,passwd,registration_id: this.reg_id});
        if(res.cd == 1){
            //loading消失
            this.setState({loadingShow: false});
            this.refs.toast.show(res.msg);
        }else{
            let r = await api.post("/config/easemob",{ticket:res.data.ticket});
            if (r.cd == 0 && r.data && r.data.group) {
                res.data.group = r.data.group;
            }else{
                res.data.group = "";
            }
            if(res.data.role == 2){//业主管家
                dispatch(actions.session.session_change({...res.data, reload:true},(str) => {
                    if (str) {
                        this.refs.toast.show(str);
                        return;
                    }
                }));
                return;
            }

            if(res.data.role == 0 && (!res.data.easemob_kefu_name||!res.data.easemob_kefu_pwd)){//物业管家(没有开通环信)
                dispatch(actions.session.session_change({...res.data, reload:true},(str) => {
                    if (str) {
                        this.refs.toast.show(str);
                        return;
                    }
                }));
                return;
            }

            //登录聊天系统
            if(res.data.role == 1 && (!res.data.easemob_kefu_name||!res.data.easemob_kefu_pwd)){
                this.setState({loadingShow: false});
                this.refs.toast.show("未开通消息账户，无法登录!");
                return;
            }

            EasemobChat.chatLogin({uName:res.data.easemob_kefu_name,uPwd:res.data.easemob_kefu_pwd}, (resStr)=>{
                //loading消失
                this.setState({loadingShow: false});
                if(resStr == 'success'){
                    dispatch(actions.session.session_change({...res.data, reload:true},(str) =>{
                        if (str) {
                            this.refs.toast.show(str);
                            EasemobChat.chatLogout(async (resStr)=>{});
                        }
                        
                    }));
                }else{
                    this.refs.toast.show("登录消息失败");
                }
            });
        }
    }

    _fotgetPassAction(){
        let {navigator} = this.props;
        navigator.push({
            title: "忘记密码",
            backButtonTitle:'',
			screen: 'housekeeperapp.forgetpassword',
			passProps: {
				// orderId
			},
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled: false
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
			// backButtonHidden: true,
		});
    }

    _showPass(){
        let {isShowPass} = this.state;

        this.setState({
            isShowPass: !isShowPass
        });
    }

    _showReg(){
        let {navigator} = this.props;
        navigator.push({
            title: "注册",
            backButtonTitle:'',
			screen: 'housekeeperapp.regindex',
			passProps: {
				// orderId
			},
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled: false
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
			// backButtonHidden: true,
		});
    }

    render() {
        let {scrollY} = this.state;

        return (
            <View style={[styles.container,{height:winH, position:'absolute',top:0}]} onStartShouldSetResponderCapture={(e) => {
                const focusField = TextInput.State.currentlyFocusedField();
                if (focusField != null && e.nativeEvent.target != focusField){
                    dismissKeyboard();
                }
            }}>
                <Animated.View
                    style={[styles.headContainer, {
                        height: windowHeight,
                        transform: [{
                            translateY: scrollY.interpolate({
                                inputRange: [ -windowHeight, 0, windowHeight],
                                outputRange: [windowHeight/2, 0, -windowHeight/3]
                            })
                        },{
                            scale: scrollY.interpolate({
                                inputRange: [ -windowHeight, 0, windowHeight],
                                outputRange: [2, 1, 1]
                            })
                        }]
                    }]}>
                        <Image style={styles.headBg} source={require('../../../img/login_header_bg.png')}/>
                </Animated.View>
                <ScrollView
                    style={styles.loginScrollContainer}
                    onScroll={Animated.event(
                      [{ nativeEvent: { contentOffset: { y: this.state.scrollY }}}]
                    )}
                    scrollEventThrottle={16}
                    keyboardShouldPersistTaps={'always'}
                    keyboardDismissMode='on-drag'>
                    <Animated.View style={{
                        position: 'relative',
                        alignItems: 'center',
                        backgroundColor: 'transparent',
                        height: windowHeight,
                        opacity: scrollY.interpolate({
                            inputRange: [-windowHeight, 0, windowHeight / 1.2],
                            outputRange: [1, 1, 0]
                        }),
                    }}>

                    </Animated.View>
                    <View style={[styles.toolsContainer,{borderTopWidth:0, borderBottomWidth:0}]}>
                        <View style={[styles.addBtn, {marginRight:14}]}>
                            <Text style={styles.titleText}>手机号</Text>
                            <TextInput
                                defaultValue={""}
                                autoFocus={false}
                                style={styles.centerInput}
                                editable = {true}
                                clearButtonMode={'while-editing'}
                                secureTextEntry={false}
                                keyboardType={'numeric'}
                                maxLength={11}
                                onChangeText={(text)=>{this.setState({phone:text})}}
                                underlineColorAndroid={'transparent'}
                                placeholder={'请输入手机号'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>
                        <View style={[styles.addBtn,{paddingRight:0, marginRight:14}]}>
                            <Text style={styles.titleText}>密码</Text>
                            <TextInput
                                style={styles.centerInput}
                                editable = {true}
                                secureTextEntry={!this.state.isShowPass}
                                underlineColorAndroid={'transparent'}
                                onChangeText={(text)=>{this.setState({passwd:text})}}
                                placeholder={'请输入密码'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        <TouchableOpacity onPress={this._showPass.bind(this)} style={{padding:15,paddingRight:22}}>
                                <Image source={this.state.isShowPass?require('../../../img/hk_login_openeye_icon.png'):require('../../../img/hk_login_closeeye_icon.png')} style={styles.rightImage}/>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View>
                        <TouchableOpacity onPress={this._fotgetPassAction.bind(this)} style={styles.forgetActionBtn}>
                            <Text style={styles.forgetText}>忘记密码</Text>
                        </TouchableOpacity>

                        <TouchableOpacity onPress={this._submitAction.bind(this)} style={styles.submitActionPhoneBtn}>
                            <Text style={styles.submitActionText}>立即登录</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.regContainer}>
                        <Text style={styles.subRegInfo}>没有账号？</Text>
                        <TouchableOpacity onPress={this._showReg.bind(this)}>
                            <Text style={styles.regText}>立即注册》</Text>
                        </TouchableOpacity>
                    </View>
                </ScrollView>
                <ToastTip ref="toast"/>
                <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
LoginIndex = connectHelper(state => state)(LoginIndex);

module.exports = LoginIndex;
